package vip.meeet.base;

import java.util.LinkedList;
import java.util.Random;
import java.util.concurrent.*;

public class BlockingConsumerProducer {
    
    private static final ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(20);
    
    private static final LinkedList<Integer> discard = new LinkedList<Integer>();
    
    private static final CountDownLatch latch = new CountDownLatch(10);
    
    public static void main(String[] args) {
        ExecutorService pool = Executors.newFixedThreadPool(10);//固定线程数执行任务,无界队列
        for(int i=0;i<10;i++){
            pool.execute(new Producer());
            pool.execute(new Consumer());
        }
        pool.shutdown();
        while(!pool.isTerminated()){//等待线程池中的任务都执行完成
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println(discard);
    }
    
    static class Producer implements Runnable{

        private Random random = new Random();

        public void run() {
            int i = 10000;
            while(i-->0){
                try {
                    int e = random.nextInt(10000);
                    boolean result = queue.offer(e, 20, TimeUnit.MILLISECONDS);
                    if(!result){
                        discard.add(e);
                    }
                    e = random.nextInt(10000);
                    result = queue.offer(e, 20, TimeUnit.MILLISECONDS);
                    if(!result){
                        discard.add(e);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            latch.countDown();
        }
        
    }
    
    static class Consumer implements Runnable{

        @Override
        public void run() {
            while(latch.getCount()>0){
                try {
                    queue.poll(1, TimeUnit.SECONDS);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        
    }

}
